package com.kjj.gift.userdetailservice;

import com.kjj.gift.domain.LoginUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    /**
     * 加载数据库中的认证的用户的信息：用户名，密码，用户的权限列表
     * @param username: 该方法把username传入进来，我们通过username查询用户的信息
     (密码，权限列表等)然后封装成 UserDetails进行返回 ，交给security 。
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LoginUser loginUser = new LoginUser(); //假装从数据库查询出来的
        loginUser.setId(1L);
        loginUser.setUsername("zs");
        loginUser.setPassword("$2a$10$RNhzhYXLtedGG74ma.rXle8GUDMiSipcYj79FmHt3xU2O83L9K/BG");
        if(loginUser == null){
            throw new UsernameNotFoundException("无效的用户名");
        }
        List<GrantedAuthority> permissions = new ArrayList<>();
        //用自己封装的类来仿造数据库数据
        return new User(username,loginUser.getPassword(),permissions);
        }
    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String securityPwd = bCryptPasswordEncoder.encode("1");
        System.out.println(securityPwd);

        System.out.println(bCryptPasswordEncoder.matches("1", securityPwd));
    }
}
